<template>
	<view class="container">
		<!-- 顶部导航栏 -->
		<uni-nav-bar fixed="true" statusBar="true" border="false" left-icon="left" title="查询队伍" @clickLeft="back"></uni-nav-bar>
		
		<!-- 筛选条件区域 -->
		<view class="sticky" :style="{'top':showNavTop+'px'}">
			<view class="uni-flex uni-row">
				<view class="flex-item ac">
					<uni-icons type="compose" size="22"></uni-icons>
					<view class="lineFlex">
						<text>城市&nbsp;</text>
						<picker mode="multiSelector" :range="citys" :range-key="'name'" :value="multiIndex" @change="bindRegionChange" @columnchange="bindRegionColumnChange">
							<view class="picker text-eclips">
								{{param.locationCityName}}
							</view>
						</picker>
					</view>
				</view>
				<view class="flex-item ac">
					<uni-icons type="compose" size="22"></uni-icons>
					<view class="lineFlex">
						<text>时间&nbsp;</text>
						<picker mode="date" :value="date" :start="startDate" :end="endDate" @change="bindDateChange">
							<view class="uni-input">{{date}}</view>
						</picker>
					</view>
				</view>
			</view>
		</view>
		
		<!-- 主内容区域 - scroll-view 直接放在 container 下 -->
		<scroll-view 
			scroll-y="true" 
			scroll-x="false" 
			:style="{height:scrollH+'px'}" 
			refresher-enabled="true" 
			:refresher-triggered="isRefreshing" 
			@refresherrefresh="onRefresh" 
			@scrolltolower="onLoadMore"
		>
			<!-- 瀑布流内容 -->
			<view class="waterfall-container" v-if="List.length>0">
				<view class="waterfall-column" ref="column1">
					<view class="foot-card" v-for="item in column1Items" :key="item.id" @tap="navgetTo('pages/schdule/schdule_detail',item.id)">
						<image class="foot-avatar" :src="item.coverUrl" mode="widthFix"></image>
						<view class="p010">
							<text class="foot-name">{{item.itineraryTitle}}</text>
							<view class="uni-flex sp_betw">
								<text class="sign-num">已报{{item.memberCount}}/{{item.userLimit}}</text>
								<view class="sign-price-list"><text class="sign-price">{{item.itineraryFee}}</text>元/人</view>
							</view>
							<view class="sign-time">
								<text>{{item.collectDate}}集合</text>
							</view>
						</view>
					</view>
				</view>
				<view class="waterfall-column" ref="column2">
					<view class="foot-card" v-for="item in column2Items" :key="item.id" @tap="navgetTo('pages/schdule/schdule_detail',item.id)">
						<image class="foot-avatar" :src="item.coverUrl" mode="widthFix"></image>
						<view class="p010">
							<text class="foot-name">{{item.itineraryTitle}}</text>
							<view class="uni-flex sp_betw">
								<text class="sign-num">已报{{item.memberCount}}/{{item.userLimit}}</text>
								<view class="sign-price-list"><text class="sign-price">{{item.itineraryFee}}</text>元/人</view>
							</view>
							<view class="sign-time">
								<text>{{item.collectDate}}集合</text>
							</view>
						</view>
					</view>
				</view>
			</view>
			
			<!-- 加载提示 -->
			<view v-if="isLoading" class="tc">{{loadMoreText}}</view>
		</scroll-view>
	</view>
</template>

<script>
	import api from '@/common/api/webapi.js'; /*api*/
	import storageUtil from '@/common/util/storageUtil.js';
	export default {
		components: {
		 
		},
		data() {
			const currentDate = this.getDate({
				format: true
			})
			return {
				date: currentDate,
				showNavTop:88,
				citys: [[],[]],
				cityCode:'',
				provinceCode:'',
				multiIndex:[0,0],
				customItem: '',
				scrollH:0,
				isRefreshing:false,
				isLoading:false,
				loadMoreText:"加载中...",
				List:[],
				column1Items: [],
				column2Items: [],
				columnHeights: [0, 0],
				param: {
					page: 1, //当前页
					limit: 10, //每页显示记录数
					PageCount: 0,
					latitude: 25.040609, //默认为昆明市经纬度坐标
					longitude: 102.712251, //默认为昆明市经纬度坐标
					cityCode:0,
					locationCityName:"",
					collectDate:"",
				},
			}
		},
		computed: {
			startDate() {
				return this.getDate('start');
			},
			endDate() {
				return this.getDate('end');
			}
		},
		onShow() {
		},
		onReady() {
			// 获取可滚动区域的高度：视口高度 - tabbar切换卡高度就是剩余的内容可滚动的。
			//如果你使用取消了原生导航栏，记着把你自定义导航栏的高度也减掉哦
			this.initScrollHeight();
		},
		onLoad(option) {
			const app = getApp()
				this.navTop = app.globalData.navTop;
				this.showNavTop = this.navTop + 44;
			if(option.param){
				let params = JSON.parse(decodeURIComponent(option.param));
				this.param.locationCityName = params.data;
				this.getPageList('onPullDownRefresh');
			} else {
				// 如果没有参数，获取用户当前位置并加载数据
				this.getUserAddress();
			}
			let cityStr = storageUtil.getStorageData("region");
			let cityArr = JSON.parse(cityStr);
			Object.entries(cityArr).map(([code, name]) => ({ code, name }));
			this.citys[0] = cityArr; 
			console.log("2222",cityArr[0]['code']);
			this.getCityCode();
		},
		watch: {
			List: {
				handler(newList) {
					if (newList.length > 0) {
						this.renderWaterfall();
					}
				},
				immediate: true
			}
		},
		methods: {
			// 初始化滚动高度
			initScrollHeight() {
				// 获取系统信息
				const sysInfo = uni.getSystemInfoSync();
				// 计算可滚动区域高度，减去固定头部高度
				// 考虑导航栏高度 + sticky元素高度
				const navHeight = this.showNavTop || 88; // 导航栏高度，使用页面中已计算的showNavTop
				const stickyHeight = uni.upx2px ? uni.upx2px(80) : 40; // sticky元素高度
				this.scrollH = sysInfo.windowHeight - navHeight - stickyHeight;
			},
			back(){
				uni.navigateBack();
			},
			// 初始化省的数据
			initData() {
			  const provinceCode = this.regionData[id];; // 假设默认选中中国
			  const provinceData = this.regionData[provinceCode];
			  this.citys[0] = Object.entries(provinceData).map(([code, name]) => ({ code, name }));
			  this.updateCityData(0); // 根据默认选中的省份更新市数据
			},
			// 更新市的数据
			updateCityData(provinceIndex) {
			  const provinceCode = this.addressData[0][provinceIndex].code;
			  const cityData = this.regionData[provinceCode];
			  this.addressData[1] = Object.entries(cityData).map(([code, name]) => ({ code, name }));
			},
			bindDateChange: function(e) {
				this.date = e.detail.value;
				this.getPageList('onPullDownRefresh');
			},
			getDate(type) {
				const date = new Date();
				let year = date.getFullYear();
				let month = date.getMonth() + 1;
				let day = date.getDate();
				if (type === 'start') {
					year = year;
				} else if (type === 'end') {
					if (month > 6) {
						year = year + 1;
					}
					year = year;
				}
				month = month > 9 ? month : '0' + month;
				day = day > 9 ? day : '0' + day;
				return `${year}-${month}-${day}`;
			},
			getCityCode(){
				// 通过当前城市名称获取对应城市的所属省份id和城市id
				api.getCityCode({params:{cityName:this.param.locationCityName}}).then(res => {
					if (res.code === 0) {
						if (res.data) {
							this.provinceCode = res.data.provinceCode;
							this.cityCode = res.data.cityCode;
							this.getCitysList(this.provinceCode);
						}
					}
				}).catch(e => {
					console.error('获取省份列表失败:', e);
				});
			},
			// 详情
			navgetTo(page, param, type) {
				if (param != undefined) {
					type = type || '';
					let data = {
						data: param,
						page: type
					}
					uni.navigateTo({
						url: "/" + page + "?param=" + encodeURI(JSON.stringify(data))
					});
				} else {
					uni.navigateTo({
						url: "/" + page
					});
				}
			},
			// 城市选择
			bindRegionChange(e) {
				let provkey = e.detail.value[0];
				let citykey = e.detail.value[1];
				this.param.locationCityName = this.citys[1][citykey]['name'];
				this.param.cityCode = this.citys[1][citykey]['code'];
				this.getPageList('onPullDownRefresh');
			},
			// 省份列选择事件
			bindRegionColumnChange(e){
				if(e.detail.column == 0){
					let proviceKey = e.detail.value;
					let curProviceCode = this.citys[0][proviceKey];
					this.getCitysList(curProviceCode['code']);
				}
			},
			getCitysList(pid){
				api.getCitysList({params:{code:pid}}).then(res => {
					if (res.code === 0) {
						if (res.data.length > 0) {
							let datas = res.data;
							this.citys[1]=res.data;
							console.log(this.provinceCode,this.cityCode);
							let provicekey = this.citys[0].findIndex(item => item.code === this.provinceCode);
							let citykey = this.citys[1].findIndex(item => item.code === this.cityCode);
							console.log("provicekey",provicekey);
							console.log("citykey",citykey);
							this.multiIndex = [provicekey,citykey];
						}
					} else {}
				}).catch()
			},
			// 逆地址解析
			getUserAddress(){
				const app = getApp()
				const qqmapsdk = app.globalData.qqmapsdk;
				// 添加错误处理和默认值
				try {
					qqmapsdk.reverseGeocoder({
						//根据经纬度获取地址信息
						location: {
							latitude: this.param.latitude,
							longitude: this.param.longitude
						},
						success: res => {
							this.param.cityCode = res.result.ad_info.city_code;
							this.param.locationCityName = res.result.address_component.city;
							storageUtil.saveStorageData('cityCode',res.result.ad_info.city_code);
							storageUtil.saveStorageData('locationCityName',res.result.address_component.city);
							this.getPageList("onPullDownRefresh");
						},
						fail: () => {
							// 如果获取位置失败，使用默认值并加载数据
							this.param.locationCityName = "昆明市";
							this.getPageList("onPullDownRefresh");
						}
					});
				} catch (e) {
					console.error('获取位置信息失败:', e);
					// 出错时使用默认值并加载数据
					this.param.locationCityName = "昆明市";
					this.getPageList("onPullDownRefresh");
				}
			},
			// 渲染瀑布流
			renderWaterfall() {
				// 清空两列内容
				this.column1Items = [];
				this.column2Items = [];
				this.columnHeights = [0, 0];
				
				// 根据标题长度估算卡片高度并分配到列
				this.List.forEach(item => {
					// 估算卡片高度（基于标题长度和图片高度）
					// 实际项目中可以根据实际内容更精确计算
					const titleHeight = Math.ceil(item.itineraryTitle.length / 12) * 40; // 假设每行显示12个字符，行高40rpx
					const estimatedHeight = 300 + titleHeight; // 基础高度 + 标题高度
					
					// 找到当前高度较小的列
					const targetColumn = this.columnHeights[0] <= this.columnHeights[1] ? 0 : 1;
										
					// 将item添加到目标列
					if (targetColumn === 0) {
						this.column1Items.push(item);
					} else {
						this.column2Items.push(item);
					}
										
					// 更新列高度
					this.columnHeights[targetColumn] += estimatedHeight;
				});
			},
			onRefresh() {  // 下拉刷新
				console.log('下拉刷新被触发');
				this.isRefreshing = true;
				this.param.page = 1;
				console.log('准备调用getPageList，页码已重置为1');
				this.getPageList('onPullDownRefresh');
			},
			onLoadMore() {  // 上拉加载
				if (this.isLoading) return;
				// 检查是否还有更多数据
				if (this.param.page >= this.param.PageCount && this.param.PageCount > 0) {
					this.loadMoreText = "没有更多数据了!";
					return;
				}
				// 增加页码并调用getPageList，加载状态由getPageList内部处理
				this.param.page = this.param.page + 1;
				this.getPageList('onReachBottom');
			},
			// 获取分页列表
			getPageList(type) {
				let _this = this;
				console.log('开始获取数据，类型:', type, '页码:', _this.param.page, '参数:', _this.param);
				let requestData = {
					params: {
						page: _this.param.page, //当前页
						size: _this.param.limit, //每页显示记录数
						locationCityName: _this.param.locationCityName,
						cityCode:'',
						collectDate:_this.date
					}
				};
				
				// 确保在请求开始时设置正确的加载状态
				if (type === "onPullDownRefresh") {
					_this.isRefreshing = true;
				}
				if (type === "onReachBottom") {
					_this.isLoading = true;
					_this.loadMoreText = "加载中...";
				}
				
				// 使用正确的Promise链结构
				console.log('准备调用API:', requestData);
				api.getItineraryPageList(requestData)
					.then(res => {
						console.log('API调用成功，响应:', res);
						if (res.code === 0) {
							// 假设API响应中包含total和pageCount等分页信息
							if (res.data.length>0) {
								let pagelist = res.data;
								if (type === "onReachBottom") {
									_this.List = _this.List.concat(pagelist);
								} else {
									_this.List = pagelist;
								}
							} else {
								if(type === "onPullDownRefresh") {
									_this.List = [];
								}else if(type == "onReachBottom"){
									_this.param.page = 1;
									_this.loadMoreText = "--到底啦--"
								}
							}
						} else {
							console.log('API返回错误状态码:', res.code, '消息:', res.message);
						}
					})
					.catch(err => {
							console.error('获取数据失败:', err);
						})
					.finally(() => {
							console.log('请求完成，重置加载状态');
							// 无论成功失败，都重置加载状态
							_this.isRefreshing = false;
						});
			},
		}
	}
</script>

<style lang="scss" scoped>
	.container {
		font-size: 14px;
		line-height: 24px;
		height: 100vh;
		overflow: hidden; /* 防止页面整体滚动 */
	}

	.index-swiper {
		width: 100%;
	}

	.index-swiper image {
		width: 100%;
		height: 100%;
		object-fit: contain;
	}
	
	.p010 {
		padding: 0 10px;
	}
	
	.bottom-wrap{
		position: relative;
		top: -60rpx;
	}
	
	.xf-wrap {
		position: relative;
		top: -60rpx;
		overflow: hidden;
	}

	.box-shadow {
		box-shadow: 2rpx 2px 2rpx $uni-text-color-grey8;
		background-color: #ffffff;
		border-radius: 20rpx;
	}

	.xf-wrap input {
		font-weight: bold;
	}

	.uni-flex {
		display: flex;
		align-items: center;
	}

	.uni-row {
		flex-direction: row;
	}

	.flex-item {
		width: 50%;
		text-align: left;
		line-height: 80rpx;
	}

	.search_btn {
		background-color: $uni-text-color-green;
		font-size: 14px;
		border: none;
		color: #fff;

	}

	.sticky {
		height: 80rpx;
		line-height: 80rpx;
		background-color: #ffffff;
		width: 100%;
		color: #888;
		position: fixed;
		top: -1rpx;
		left: 0;
		right: 0;
		z-index: 999;
		padding: 0 15px;
		margin-bottom: 30rpx;
		box-shadow: 2rpx 2px 2rpx $uni-text-color-greye;
	}

	.sticky text {
		color: $uni-text-color-grey8;
		text-overflow: ellipsis;
	}

	.waterfall-container {
		width: 100%;
		display: flex;
		justify-content: space-between;
		padding: 0 15px;
		box-sizing: border-box;
		padding-top: 100rpx;
	}
	
	.waterfall-column {
		width: calc(50% - 15rpx);
	}
	
	.foot-card {
		width: 100%;
		background-color: #fff;
		border-radius: 20rpx;
		position: relative;
		margin-bottom: 30rpx;
		box-shadow: 2rpx 2rpx 10rpx $uni-text-color-grey8;
		box-sizing: border-box;
	}

	.foot-avatar {
		width: 100%;
		border-top-right-radius: 20rpx;
		border-top-left-radius: 20rpx;
	}

	.foot-name {
		font-size: 28rpx;
		color: #000;
	}

	.sign-num {
		font-size: 26rpx;
		color: $uni-text-color-grey8;
	}

	.sign-price-list {
		font-size: 26rpx;
		color: $uni-text-color-grey8;
	}

	.sign-price {
		color: $uni-text-color-red;
	}

	.sign-time {
		position: absolute;
		top: 10rpx;
		width: 98%;
		left: 0;
		right: 0;
		margin: auto;
		background-color: rgba(0, 0, 0, 0.6);
		height: 45rpx;
		color: #fff;
		font-size: 24rpx;
		border-radius: 20rpx;
		padding: 0 10rpx;
		box-sizing: border-box;
	}
</style>